<script lang="ts">
  import { getSearchStock } from '../api/index';
  import config from '../config/index';
  import type { AssociateArr } from '../types/inputSearch';
  import { debounce, errorReport, sendStat } from '../utils/tools';

  import InputAssociate from './InputAssociate.svelte';
  import { createEventDispatcher } from 'svelte';
  const emit = createEventDispatcher();
  let inputValue: string = '';
  let isError: boolean = false;
  let associateArr: AssociateArr[] = [];
  let selectedIndex: number = 0;
  let isFocus: boolean = false;
  let inputAssociate;
  // 获取联想内容
  const getSearchStockApi = () => {
    getSearchStock({
      pattern: inputValueTrim,
      reqLockKey: 'reqSearchStock',
      appname: 'vtuber'
    })
      .then((res) => {
        if (!res.status_code) {
          const hSMarkets: string[] = config.marketCodeMap.HS;
          associateArr = res.data
            .map(({ stockCode, stockName, marketId }) => {
              if (hSMarkets.includes(marketId)) {
                return {
                  stockCode,
                  stockName
                };
              }
            })
            .filter(Boolean);
          selectedIndex = 0;
          isError = !!!associateArr.length;
          if (!inputValueTrim) {
            isError = false;
          }
        } else {
          throw new Error(`status_code:${res.status_code},status_msg:${res.status_msg}`);
        }
      })
      .catch((error) => {
        errorReport({
          name: `获取联想内容接口报错 ${error.name}`,
          message: error.message,
          stack: error.stack
        });
      });
  };

  const getSearchStockApiDebounce = debounce(getSearchStockApi, 100);

  //诊股
  const stockDiagnosis = (index: number) => {
    const stock = associateArr[index];
    if (stock) {
      const { stockCode, stockName } = stock;
      emit('stockDiagnosis', { stockCode, stockName });
      sendStat('_dhym_srk');
      inputValue = '';
    }
  };
  //   选择联想词
  const selectAssociate = ({ detail: { index } }) => {
    stockDiagnosis(index);
  };

  const handleKeyDown = (event) => {
    const enterFn = () => {
      stockDiagnosis(selectedIndex);
    };
    const downFn = () => {
      if (selectedIndex < associateArr.length - 1) {
        selectedIndex++;
      }
    };
    const upFn = () => {
      if (selectedIndex > 0) {
        selectedIndex--;
      }
    };
    const keyCodeOptions = {
      13: enterFn,
      40: downFn,
      38: upFn
    };
    if (keyCodeOptions[event.keyCode]) {
      event.preventDefault();
      keyCodeOptions[event.keyCode]();
    }
  };

  $: inputValueTrim = inputValue.trim();
  $: {
    if (inputValueTrim) {
      getSearchStockApiDebounce();
    } else {
      isError = false;
    }
  }
  $: {
    if (selectedIndex !== -1) {
      inputAssociate && inputAssociate.position();
    }
  }
</script>

<!-- svelte-ignore a11y-click-events-have-key-events -->
<div
  class="input-search-container"
  on:click={(e) => {
    e.stopPropagation();
  }}
  on:mousedown={(e) => {
    e.stopPropagation();
  }}
>
  {#if inputValueTrim && associateArr.length && isFocus}
    <InputAssociate
      bind:this={inputAssociate}
      {associateArr}
      inputValue={inputValueTrim}
      {selectedIndex}
      on:selectAssociate={selectAssociate}
    />
  {/if}
  <div class="input-search {isError ? 'error' : ''}">
    <input
      type="text"
      autocomplete="off"
      placeholder="输入股票名称/代码提问试一试"
      class="input"
      on:focus={() => {
        isFocus = true;
        emit('setIsFocus', { isFocus });
      }}
      on:blur={() => {
        setTimeout(() => {
          isFocus = false;
          emit('setIsFocus', { isFocus });
        }, 200);
      }}
      bind:value={inputValue}
      on:keydown={handleKeyDown}
    />
    {#if isError}
      <div class="tips">仅支持沪深A股诊断</div>
    {/if}
  </div>
</div>

<style lang="less">
  .input-search-container {
    position: relative;
    .input-search {
      box-sizing: border-box;
      width: 280px;
      margin-top: 10px;
      position: relative;
      background-color: rgba(72, 81, 106, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.5);
      &.error {
        border-color: #ff2929;
        .input {
          width: 45%;
        }
      }
      .input {
        -webkit-appearance: none;
        width: 100%;
        height: 36px;
        background-color: rgba(72, 81, 106, 0);
        border-radius: 2px;
        outline: none;
        padding: 8px 12px;
        box-sizing: border-box;
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #f2f2f2;
        letter-spacing: 0;
        line-height: 20px;
        font-weight: 400;
        border: 0;
        &::placeholder {
          opacity: 0.5;
          font-family: PingFangSC-Regular;
          font-size: 16px;
          color: #ffffff;
          letter-spacing: 0;
          line-height: 20px;
          font-weight: 400;
        }
      }
      .tips {
        position: absolute;
        font-family: PingFangSC-Regular;
        font-size: 12px;
        color: #ff2929;
        letter-spacing: 0;
        line-height: 16px;
        font-weight: 400;
        right: 0;
        top: 50%;
        margin-right: 12px;
        transform: translate(0, -50%);
      }
    }
  }
</style>
